package com.adjy.pathbuilders.screens;

import static com.adjy.pathbuilders.commons.Preconditions.check;
import static com.adjy.pathbuilders.commons.Preconditions.checkNotNull;

import java.util.List;

import android.view.MotionEvent;

public class PageManager {
	
	private List<ScreenPage> pages;
	private ScreenPage currentPage;
	
	public PageManager(List<ScreenPage> pages) {
		checkNotNull(pages, "pages must not be null.");
		check(pages.size() >= 1, "pages must not be empty.");
		
		this.pages = pages;
		configurePages(this.pages);
		currentPage = pages.get(0);
	}
	
	private void configurePages(List<ScreenPage> pages) {
		if (pages.size() > 1) {
			configureFirst(pages);
			
			for (int i = 1; i < pages.size() - 1; i++) {
				pages.get(i).setPrevious(pages.get(i - 1));
				pages.get(i).setNext(pages.get(i + 1));
			}
			
			configureLast(pages);
		}
	}
	
	private void configureFirst(List<ScreenPage> pages) {
		pages.get(0).setNext(pages.get(1));
	}
	
	private void configureLast(List<ScreenPage> pages) {
		pages.get(pages.size() - 1).setPrevious(pages.get(pages.size() - 2));
	}
	
	public void reset() {
		// reset the class and the pages
		for (ScreenPage page : pages) {
			page.reset();
		}
		currentPage = pages.get(0);
	}
	
	public void manage(MotionEvent event) {
		// reset the class and the pages
		currentPage.input(event);
		ScreenPage last = currentPage; 
		currentPage = currentPage.getNextPage();
		last.reset();
	}
	
	public ScreenPage getCurrentPage() {
		return currentPage;
	}
}
